import React, {Component} from 'react';
import {
    Modal,
    Toast,
    Flex,
    Button,
    List,
    Checkbox,
    InputItem,
    Picker,
    Switch
} from 'antd-mobile';
import { invoice_all, save_btn, required, invoice_box } from './invoice.less'
import { connect } from 'dva';
import { createForm } from 'rc-form';
import NavTopBar from '../../components/NavTopBar/NavTopBar';
import MyScroll from '../../components/MyScroll/MyScroll';
const Item = List.Item;

// 纳税人识别号、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
function checkTaxpayerId(taxpayerId){
    if(taxpayerId!="" && taxpayerId.length===15){
        var addressCode = taxpayerId.substring(0,6);
        // 校验地址码
        var check = checkAddressCode(addressCode);
        if(!check){
            return false;
        }
        // 校验组织机构代码
        var orgCode = taxpayerId.substring(6,9);
        check = isValidOrgCode(orgCode);
        if(!check){
            return false;
        }
        return true;
    }else{
        return false;
    }
}

function isValidOrgCode(value){
    if(value!=""){
        var part1=value.substring(0,8);
        var part2=value.substring(value.length-1,1);
        var ws = [3, 7, 9, 10, 5, 8, 4, 2];
        var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var reg = /^([0-9A-Z]){8}$/;
        if (!reg.test(part1))
        {
            return true
        }
        var sum = 0;
        for (var i = 0; i< 8; i++)
        {
            sum += str.indexOf(part1.charAt(i)) * ws[i];
        }
        var C9 = 11 - (sum % 11);
        var YC9=part2+'';
        if (C9 == 11) {
            C9 = '0';
        } else if (C9 == 10) {
            C9 = 'X' ;
        } else {
            C9 = C9+'';
        }
        return YC9!=C9;
    }
}

function checkAddressCode(addressCode){
    var provinceAndCitys={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",
        31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",
        45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",
        65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
    var check = /^[1-9]\d{5}$/.test(addressCode);
    if(!check) return false;
    if(provinceAndCitys[parseInt(addressCode.substring(0,2))]){
        return true;
    }else{
        return false;
    }

}



class Invoice extends Component {
    constructor(props){
        super(props);
        this.state = {
            isDefault: true,
            invData: {},
        };
        this.query = {};

    }

    componentWillUnmount(){
        this.changeInvoice({state: 1, title: 3});
    }

    componentDidMount(){
        this.props.location.search.replace(/([^?&=]+)=([^?&=]*)/g, (m, p1, p2) => this.query[p1] = p2);
        const { orderAddress, match, dispatch } = this.props;
        match.params.invId ? this.props.dispatch({ type:"invoice/getDetailEFF", obj:{invoiceId:match.params.invId} }).then((res)=>{
            if (res.code == 200) {
                console.log()
                const r=res.ret.list[0]
                this.props.form.setFieldsValue({
                    code: r.invCode,
                    company: r.invCompany,
                    regAddr: r.invRegAddr,
                    isDefault: r.isDefault,
                    isPass: r.isPass,
                    titleName:r.titleName,
                    regPhone:r.invRegPhone,
                    regBname:r.invRegBname,
                    regBaccount:r.invRegBaccount,
                    invId:r.invId
                });
            } else {
                Toast.info(result.msg);
            }
        }):'';
    }

    changeInvoice = (obj) => {
        this.props.dispatch({ type:"invoice/changeInvoice", obj })
    }

    onSubmit = () => {
        const fieldsValue = this.props.form.getFieldsValue();
        const { state, title, content, company="", code="", regAddr="", regPhone="", regBname="", regBaccount="" } = this.props.invoice;
        const isDefault=fieldsValue.isDefault ? 1 : 0;
        if(state != 2 && title == 4){
            if (!fieldsValue.company || fieldsValue.company == '') {
                Toast.info('请填写单位名称');
                return;
            }
            if (!fieldsValue.code || fieldsValue.code.trim() == '') {
                Toast.info('请填写纳税人识别号');
                return;
            }

            // if ( fieldsValue.code.length != 15 || fieldsValue.code.length != 18 ) return Toast.info('请填写正确的纳税人识别号');
            // if ( !checkTaxpayerId(fieldsValue.code) ) return Toast.info('请填写正确的纳税人识别号')

            //if (!content || content == ''){
            //    Toast.info('请填写发票内容');
            //    return;
            //}
            if (!fieldsValue.invId || fieldsValue.invId == ''){
                this.props.dispatch({ type:'invoice/modifyEFF', obj:{  state, title,isDefault, company: fieldsValue.company, code: fieldsValue.code, LzID: this.query.storeId } } )
            }else {
                this.props.dispatch({ type:'invoice/modifyEFF', obj:{  state, title,isDefault, invoiceId:fieldsValue.invId, company: fieldsValue.company, code: fieldsValue.code, LzID: this.query.storeId } } )
            }
        }else if(state==2){
            if (!fieldsValue.company || fieldsValue.company == '') {
                Toast.info('请填写单位名称');
                return;
            }
            if (!fieldsValue.code || fieldsValue.code == '') {
                Toast.info('请填写纳税人识别号');
                return;
            }
            if (!fieldsValue.regPhone || fieldsValue.regPhone == '') {
                Toast.info('请填写注册电话');
                return;
            }
            // if (!/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/.test(fieldsValue.regPhone.replace(/\s/g,''))) {
            //     Toast.info('手机号格式不正确');
            //     return;
            // }
            if (!fieldsValue.regAddr || fieldsValue.regAddr == '') {
                Toast.info('请填写注册地址');
                return;
            }
            if (!fieldsValue.regBname || fieldsValue.regBname == '') {
                Toast.info('请填写开户银行');
                return;
            }
            if (!fieldsValue.regBaccount || fieldsValue.regBaccount == '') {
                Toast.info('请填写银行账户');
                return;
            }
            //if (!content || content == ''){
            //    Toast.info('请填写发票内容');
            //    return;
            //}
            if (!fieldsValue.invId || fieldsValue.invId == ''){
                this.props.dispatch({ type:'invoice/modifyEFF', obj:{ state: 2,regBaccount:fieldsValue.regBaccount,regBname:fieldsValue.regBname,regAddr:fieldsValue.regAddr, code:fieldsValue.code,company:fieldsValue.company,isDefault, regPhone: fieldsValue.regPhone.replace(/\s/g,'') } } )

            }else {
                this.props.dispatch({ type:'invoice/modifyEFF', obj:{ state: 2, regBaccount:fieldsValue.regBaccount,regBname:fieldsValue.regBname,regAddr:fieldsValue.regAddr,code:fieldsValue.code,company:fieldsValue.company,isDefault,invoiceId:fieldsValue.invId, regPhone: fieldsValue.regPhone.replace(/\s/g,'') } } )

            }
        }else if(state != 2&&title==3){
            //if (!content || content == ''){
            //    Toast.info('请填写发票内容');
            //    return;
            //}
            // if (!fieldsValue.titleName || fieldsValue.titleName == '') {
            //     Toast.info('请填写抬头名称');
            //     return;
            // }
            if (!fieldsValue.invId || fieldsValue.invId == '') {
                this.props.dispatch({ type:'invoice/modifyEFF', obj:{ state: 1, title,isDefault, titleName: fieldsValue.titleName || '个人发票' } } )

            }else {
                this.props.dispatch({ type:'invoice/modifyEFF', obj:{ state: 1, title,isDefault,invoiceId:fieldsValue.invId,titleName: fieldsValue.titleName } } )

            }
        }
    }



    render() {
        const { dispatch, invoice = {} } = this.props;
        const { getFieldProps } = this.props.form;
        const { state = 1, title = 3, invoiceBasic = {}, invTitle, content, company = "", code = "", regAddr = "", regPhone = "", regBname = "", regBaccount = "" } = invoice;
        const {invoicesContent = []} = invoiceBasic;
        const isDefault=true;
        const invId=getFieldProps('invId').value || '';
        //console.log(invoice, "invoice");
        //console.log(this.props.accountManagement.invoiceList, this.props.accountManagement.invoiceList.invoiceBasic, "内容。。。。");
        return (
            <Flex style={{
                height:"100%"
            }} direction="column"
                // className={addressList}
            >
                <NavTopBar dispatch={dispatch} title="发票信息"/>

                <MyScroll>

                   <div className={invoice_all}>
                       <div className="invoice_type">
                           <div className="title">
                               发票类型
                           </div>
                           <Flex className="body">
                            {
                                invId !=''&& state==2 ?
                                    <div  className={ state==2 ? "select_type_gray" : "" }>普通发票</div>
                                    :<div onClick={()=>{this.changeInvoice({ state:1 })}} className={ state==1 ? "select_type" : "" }>普通发票</div>

                            }
                               {/* <div onClick={()=>{this.changeInvoice({ state:3 })}} className={ state==3 ? "select_type" : "" }>电子发票</div> */}
                            {
                                invId !=''&& state==1 ?
                                    <div className={ state==1 ? "select_type_gray" : "" }>增值税专用发票</div>
                                   : <div onClick={()=>{this.changeInvoice({ state:2 })}} className={ state==2 ? "select_type" : "" }>增值税专用发票</div>

                            }
                           </Flex>
                       </div>

                       <div style={{ padding:"0.2rem 0rem" }}>

                           <div className="invoice_type">
                               <div className="title">
                                   发票抬头
                               </div>
                               {
                                   state != 2 ?
                                   <Flex className="body">
                                       <div
                                           onClick={()=>{
                                               this.changeInvoice({ title:3 })
                                           }}
                                           className={ title == 3 ? "select_type" : "" }>个人</div>
                                       <div
                                           onClick={()=>{
                                               this.changeInvoice({ title:4 })
                                           }}
                                           className={ title == 4 ? "select_type" : "" }
                                       >
                                           单位
                                       </div>
                                   </Flex> : ""
                               }
                           </div>

                           <div className="input">
                               {
                                   title == 4 && state == 1 ?
                                   <div>
                                       <InputItem
                                           {...getFieldProps('company')}
                                           clear
                                           placeholder="请输入单位名称"
                                       ></InputItem>

                                       <InputItem
                                           {...getFieldProps('code')}
                                           clear
                                           placeholder="请输入纳税人识别号"
                                       ></InputItem>
                                   </div> : ""
                               }

                                {
                                    state != 2&&title==3 ?
                                    <div>
                                        <InputItem
                                            {...getFieldProps('titleName')}
                                            clear
                                            placeholder="请准备填写抬头名称"
                                        ></InputItem>
                                        </div> : ""
                                }
                               {
                                   state == 2 ?
                                       <div>
                                           <InputItem
                                               {...getFieldProps('company')}
                                               className={ required }
                                               placeholder="单位名称"
                                               extra="*"
                                           ></InputItem>

                                           <InputItem
                                               {...getFieldProps('code')}
                                               className={ required }
                                               placeholder="纳税人识别号"
                                               extra="*"
                                           ></InputItem>

                                           <InputItem
                                               {...getFieldProps('regAddr')}
                                               placeholder="注册地址"
                                               className={ required }
                                               extra="*"
                                           ></InputItem>

                                           <InputItem
                                               className={ required }
                                               {...getFieldProps('regPhone')}
                                               type='phone'
                                               placeholder="注册电话"
                                               extra="*"
                                           ></InputItem>
                                           <InputItem
                                               {...getFieldProps('regBname')}
                                               placeholder="开户银行"
                                               className={ required }
                                               extra="*"
                                           ></InputItem>
                                           <InputItem
                                               {...getFieldProps('regBaccount')}
                                               placeholder="银行账号"
                                               className={ required }
                                               extra="*"
                                           ></InputItem>
                                       </div> : ""
                               }

                           </div>

                       </div>

                       <div className="invoice_type">
                            {/*
                             <div className="title">
                             发票内容
                             </div>
                             <div className="body">
                             <div onClick={()=>{this.changeInvoice({ content: 1 })}} className={ content == 1 ? "select_type" : "" }>电脑配件</div>
                             <div onClick={()=>{this.changeInvoice({ content: 4 })}} className={ content == 4 ? "select_type" : "" }>办公用品</div>
                             <div onClick={()=>{this.changeInvoice({ content: 2 })}} className={ content == 2 ? "select_type" : "" }>明细</div>
                             <div onClick={()=>{this.changeInvoice({ content: 3 })}} className={ content == 3 ? "select_type" : "" }>耗材</div>
                                {
                                    this.props.accountManagement.invoiceList.invoiceBasic && this.props.accountManagement.invoiceList.invoiceBasic['发票内容'].map(v => {
                                        return (<div style={{float: "left"}} key={v.id} onClick={()=>{this.changeInvoice({ content: v.id })}} className={ content == v.id ? "select_type" : "" }>{ v.name }</div>);
                                    })
                                }
                            </div>
                            */}
                            <div className="defaultRise">

                                <Item
                                    // onClick={()=>{
                                    //     dispatch(routerRedux.push("/OrderInvoice"))
                                    // }}
                                    // arrow="horizontal"
                                    style={{height: '1.2rem',fontSize:'0.28rem'}}
                                    extra={
                                        <Switch
                                            {...getFieldProps('isDefault', {
                                                initialValue: !!isDefault,
                                                valuePropName: 'checked',
                                            })}
                                            // onClick={(checked) => {
                                            //     switchChecked = checked;
                                            //     this.invoices[v.storeId] = checked ? "invoiceID" : 0;
                                            //     this.setState({change: !this.state.change});
                                            // }}
                                        />
                                        }
                                        >
                                    是否设为默认抬头
                                </Item>
                                    <InputItem style={{display:"none"}}
                                        {...getFieldProps('invId')}
                                        type="hidden"
                                    ></InputItem>

                            </div>

                       </div>

                   </div>
                </MyScroll>

                <Button className={save_btn} onClick={this.onSubmit} type='primary'>确定</Button>
            </Flex>

        )


    }
}

export default connect(({ invoice, accountManagement, my }) => ({ invoice, accountManagement, my }))(createForm()(Invoice));
